// Modules to control application life and create native browser window
const {app, BrowserWindow, ipcMain, dialog } = require('electron')
const DataStore = require('./renderer/MusicDataStore')

const myStore = new DataStore({
  'name': 'Music Data'
})
class AppWindow extends BrowserWindow {
  constructor(config,fileLocation){
    const basicConfig = {
      width:800,
      height:600,
      webPreferences:{
        nodeIntegration:true
      }
    }
    const finalConfig = {...basicConfig, ...config}
    super(finalConfig)
    this.loadFile(fileLocation)
    this.once('ready-to-show', () => {
      this.show()
    })
  }
}

app.on('ready',()=>{
  const mainWindow = new AppWindow({},'./renderer/index.html')
  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.send('getTracks', myStore.getTracks())
  })
  ipcMain.on('addMusicWindow', () => {
    const addWindow = new AppWindow({
      width:600,
      height:500,
      parent: mainWindow
    },'./renderer/add.html')
  })

  ipcMain.on('addTracks', (event, tracks) => {
    const updatedTracks = myStore.addTracks(tracks).getTracks()
    mainWindow.send('getTracks', updatedTracks)
   })
   
  ipcMain.on('deleteTrack', (event, id) => {
    const updatedTracks = myStore.deleteTrack(id).getTracks()
    event.reply('getTracks', updatedTracks)
  })

  ipcMain.on('openMusicFile', (event) => {
    dialog.showOpenDialog({
      properties:['openFile', 'multiSelections'],
      filters: [
        { name: 'Music', extensions: ['mp3'] },
      ]
    }).then(result => {
      if(result){
        event.reply('selectedFile',result.filePaths)
      }
    }).catch(err => {
      console.log(err)
    })

  })
})